package com.woniuxy.core.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.woniuxy.core.service.AlipayService;
import com.woniuxy.entity.PaymentRecord;
import com.woniuxy.entity.ShopOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hq
 * @Date 2025/7/14$ 23:07$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {
    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.merchantPrivateKey}")
    private String privateKey;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    @Value("${alipay.returnUrl}")
    private String returnUrl;
    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;
    @Value("${alipay.signType}")
    private String signType;
    @Value("${alipay.charset}")
    private String charset;
    @Override
    public Map<String, String> createPayment(ShopOrder order, PaymentRecord paymentRecord) {
        // 创建AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipay.com/gateway.do",
                appId,
                privateKey,
                "json",
                "UTF-8",
                alipayPublicKey,
                "RSA2"
        );

        // 创建请求对象
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

        // 设置业务参数
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(paymentRecord.getTransactionId());
        model.setSubject("订单支付-" + order.getOrderNumber());
        model.setTotalAmount(paymentRecord.getAmount().toString());
        model.setBody("商品描述");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        // 设置回调URL
        request.setNotifyUrl(notifyUrl);
        try {
            // 调用SDK生成支付参数
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            Map<String, String> result = new HashMap<>();
            result.put("paymentParams", response.getBody());
            result.put("transactionId", paymentRecord.getTransactionId());
            return result;
        } catch (AlipayApiException e) {
            log.error("创建支付宝支付失败", e);
            throw new RuntimeException("支付创建失败");
        }
    }
}
